package leetcode.code0056;

import java.util.Arrays;

public class Solution extends Solution56 {

	@Override
	public int[][] merge(int[][] intervals) {
		Arrays.sort(intervals, (o1, o2) -> {
			return o1[0] - o2[0];
		});
		int p = 0; // 向intervals上p位置合并区间
		for (int i = 1; i < intervals.length; i++) {
			if (f(intervals[p], intervals[i])) {// 能合并, 合并的结果给p持有 , 继续向p合并i
				intervals[p][1] = Math.max(intervals[p][1], intervals[i][1]); // 区间能合并, 接入intervals[i]的区间尾部
			} else {
				intervals[++p] = intervals[i];// 不能合并, p向下移动一位 , 将i位置给p
			}
		}
		int[][] ans = new int[p + 1][2];
		for (int i = 0; i <= p; i++) {
			ans[i] = intervals[i];
		}
		return ans;
	}

	private boolean f(int[] arr1, int[] arr2) {
		int left = Math.max(arr1[0], arr2[0]);
		int right = Math.min(arr1[1], arr2[1]);
		if (left <= right) {
			return true;
		}
		return false;
	}

	private int[] farr(int[] arr1, int[] arr2) {
		int left = Math.max(arr1[0], arr2[0]);
		int right = Math.min(arr1[1], arr2[1]);
		int[] ans = new int[3];
		if (left <= right) {
			ans[2] = 1;
			ans[0] = Math.min(arr1[0], arr2[0]);
			ans[1] = Math.max(arr1[1], arr2[1]);
		}
		return ans;
	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
	}

}
